package com.ruoyi.project.applet.util;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import org.springframework.format.annotation.DateTimeFormat;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class CustomDateFormat {

    public static class CustomDateDeserializer extends JsonDeserializer<Date> {
        private final String[] dateFormats = new String[]{
                "yyyy-MM-dd HH:mm:ss",    // 第一种格式
//                "yyyy-MM-ddTHH:mm:ss",    // 第一种格式
        };

        @Override
        public Date deserialize(JsonParser p, DeserializationContext ctxt) throws IOException, JsonProcessingException {
            String dateStr = p.getText();
            for (String format : dateFormats) {
                try {
                    dateStr = dateStr.replace("T", " ");
                    SimpleDateFormat sdf = new SimpleDateFormat(format);
                    return sdf.parse(dateStr);
                } catch (ParseException e) {
                    // 如果当前格式不匹配，继续尝试下一个格式
                }
            }
            return null;  // 如果无法解析，返回null或抛出异常
        }
    }

    public static class CustomDateSerializer extends JsonSerializer<Date> {
        private final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        @Override
        public void serialize(Date value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
            gen.writeString(dateFormat.format(value)); // 输出统一格式
        }
    }

    // 在你的类字段上使用自定义的序列化和反序列化器
    public static class MyModel {
        @JsonSerialize(using = CustomDateSerializer.class)
        @JsonDeserialize(using = CustomDateDeserializer.class)
        @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") // Spring的默认日期格式
        private Date date;

        // getter 和 setter
        public Date getDate() {
            return date;
        }

        public void setDate(Date date) {
            this.date = date;
        }
    }
}

